package servlet;

import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //接受
        String rememberMe = request.getParameter("rememberMe");
        User user = userService.login(username, password);
        if (user != null) {
            //前端记住我
            if("1".equals(rememberMe)){
                Cookie cookieUsername = new Cookie("username", username);
                Cookie cookiePassword = new Cookie("password", password);
                cookieUsername.setMaxAge(7*24*3600);
                cookiePassword.setMaxAge(7*24*3600);
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);

            }else{
                Cookie cookieUsername = new Cookie("username", null);
                Cookie cookiePassword = new Cookie("password", null);
                cookieUsername.setMaxAge(0);
                cookiePassword.setMaxAge(0);
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);

            }


            HttpSession session = request.getSession();
            session.setAttribute("LOGIN_USER", user);
            response.sendRedirect( "selectAll");
        } else {
            String msg = "用户名或者密码错误！";
            request.setAttribute("LOGIN_MSG", msg);
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }
}